package com.intelligentmeterreadingsys.report.activity;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.otherequipment.activity.EquipementAddActivity;
import com.intelligentmeterreadingsys.povo.ResourcesPoVo;
import com.intelligentmeterreadingsys.report.db.ReportDao;
import com.intelligentmeterreadingsys.util.BitmapUtil;
import com.intelligentmeterreadingsys.util.FileNameUtil;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ViewSwitcher.ViewFactory;

/**
 * 工程单添加图片
 * 
 * @author king
 * 
 */
public class OrderImageActivity extends Activity implements
		OnItemSelectedListener, ViewFactory {
	public static final int ITEM0 = Menu.FIRST;// 系统值
	private static final int REQUEST_CODE_TAKE_IMAGE = 1;
	private ImageSwitcher imgsw;

	private Gallery gallery;

	private Context mContext;

	private String otherid = null;
	private String status = null;

	public boolean b = false;

	public int poston;// 当前位置
	public ArrayList<String> imagepath = new ArrayList<String>();
	public String classname;
	public String imgpath = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.image_switcher_activity);
		
		imgsw = (ImageSwitcher) findViewById(R.id.imgswch1);
		gallery = (Gallery) findViewById(R.id.gallery);
		init();
		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();

		otherid = bundle.getString("otherid");
		classname = bundle.getString("classname");
		
		status = bundle.getString("status");
		if (otherid != null && !otherid.equals("")) {
			ReportDao dao = new ReportDao(this);
			imagepath = dao.queryImagePath(otherid);
			dao.close();
			if (imagepath == null || imagepath.size() < 1) {
				System.out.println("----------------->>>>>>>>>>>");
				Photograph();
			}

		}
		
	}

	@Override
	/**
	 * ʵ�ֵ�ViewFactory�ӿ�
	 */
	public View makeView() {
		ImageView i = new ImageView(this);
		i.setBackgroundColor(0xFF000000);
		i.setScaleType(ImageView.ScaleType.FIT_CENTER);
		i.setLayoutParams(new ImageSwitcher.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		return i;

	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
			long arg3) {
		
		if (!b) {
			imgsw.setImageResource(R.drawable.contraband);
		} else {
			Uri uri = Uri.parse(imagepath.get(arg2));
			imgsw.setImageURI(uri);
		}

		poston = arg2;

	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {

	}

	public class ImageAdapter extends BaseAdapter {
		public ImageAdapter(Context c) {
			mContext = c;
		}

		@Override
		public int getCount() {

			if (!b) {
				System.out.println("----------------");
				return 1;
			}
			return imagepath.size();

		}

		@Override
		public Object getItem(int position) {

			return position;
		}

		@Override
		public long getItemId(int position) {

			return position;
		}

		@Override
		/**
		 * ���ImageView
		 */
		public View getView(int position, View convertView, ViewGroup parent) {

			ImageView i = new ImageView(mContext);
			if (!b) {
				i.setImageResource(R.drawable.contraband);
			} else {
				FileInputStream f;
				try {
					f = new FileInputStream(imagepath.get(position));
					FileDescriptor fd = f.getFD();

					BitmapFactory.Options options = new BitmapFactory.Options();
					options.inJustDecodeBounds = true;
					BitmapFactory.decodeFileDescriptor(fd, null, options);

					options.inSampleSize = BitmapUtil.computeSampleSize(
							options, 80, 128 * 128);

					options.inJustDecodeBounds = false;
					Bitmap bm = BitmapFactory.decodeStream(f, null, options);

					i.setImageBitmap(bm);
				} catch (FileNotFoundException e) {

					e.printStackTrace();
				} catch (IOException e) {

					e.printStackTrace();
				}

			}

			i.setAdjustViewBounds(true);
			i.setLayoutParams(new Gallery.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));// ͼƬ��С
			if (b)
				i.setBackgroundResource(R.drawable.contraband);// ͼƬ����
			return i;
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, ITEM0, 0, "拍照");
		menu.add(0, ITEM0 + 1, 0, "删除");
		menu.findItem(ITEM0 + 1);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		if (item.getItemId() == ITEM0) {
			Photograph();
		} else if (item.getItemId() == ITEM0 + 1) {

			delect();
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_TAKE_IMAGE) {

			if (resultCode == RESULT_OK) {
				Bitmap bitmap = null;
				try {
					FileInputStream fis = new FileInputStream(imgpath);

					bitmap = BitmapFactory.decodeStream(fis);
					imagepath.add(imgpath);
					b = true;
					init();

				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}

			} else if (resultCode == RESULT_CANCELED) {

				b = false;
				init();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onRestart() {
		System.out.println("onRestart");

		super.onRestart();
	}

	/**
	 * 初始化
	 */
	public void init() {
		imgsw.removeAllViews();
		imgsw.setFactory(this);
		imgsw.setInAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_in));
		imgsw.setOutAnimation(AnimationUtils.loadAnimation(this,
				android.R.anim.fade_out));
		gallery.setAdapter(new ImageAdapter(this));
		gallery.setOnItemSelectedListener(this);
	}

	/**
	 * 删除一张照片
	 */
	public void delect() {
		if (!b) {
			Toast.makeText(this, "没有图片不能进行此抄作", Toast.LENGTH_LONG).show();
			return;
		}

		File file = new File(imagepath.get(poston));
		file.delete();
		imagepath.remove(poston);
		if (imagepath.size() < 1) {
			b = false;
		}
		init();

		Toast.makeText(this, "删除成功", Toast.LENGTH_LONG).show();

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent = null;
			if (classname.equals("ReportAddActivity")) {
				intent = new Intent(OrderImageActivity.this,
						ReportNoRFIDActivity.class);
			} else if (classname.equals("ReportNoRFIDActivity")) {
				intent = new Intent(OrderImageActivity.this,
						ReportNoRFIDActivity.class);
			} else if (classname.equals("OrderOtherActivity")) {
				intent = new Intent(OrderImageActivity.this,
						OrderOtherActivity.class);
			} else if (classname.equals("EquipementAddActivity")) {
				intent = new Intent(OrderImageActivity.this,
						EquipementAddActivity.class);
			}

			Bundle bundle = new Bundle();
			bundle.putStringArrayList("imgpath", imagepath);
			intent.putExtras(bundle);
			setResult(RESULT_OK, intent);
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 拍照
	 */
	public void Photograph() {

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		FileNameUtil f = new FileNameUtil(this);
		imgpath = f.Orderimgpath();
		if (status.equals("2")) {
			imgpath = f.Waterimgpath();
		}
		if (status.equals("4")) {
			imgpath = f.Equipement();
		}

		if (imgpath == null) {
			Toast.makeText(OrderImageActivity.this, "SD卡不可用", Toast.LENGTH_LONG)
					.show();
			return;
		}
		String fileName = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date()) + ".png";
		imgpath = imgpath + "/" + fileName;
		intent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(new File(imgpath)));
		startActivityForResult(intent, REQUEST_CODE_TAKE_IMAGE);

	}

}
